class SitesController < ApplicationController
  before_filter :check_authentication, :only => [:new, :create]
  before_filter :admin_authentication, :except => [:new, :create, :popular]
  
  def index
    list
    render :action => 'list'
  end
  
  def popular
    @sites = Site.most_popular
  end
  
  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
  :redirect_to => { :action => :list }
  
  def list
    @site_pages, @sites = paginate :sites, :per_page => 10
  end
  
  def list_unapproved
    @site_pages, @sites = paginate :sites, :per_page => 10, 
        :conditions => ["approved <> true"], :order => "created_at DESC"
    render :template => "sites/list"
  end
  
  def show
    @site = Site.find(params[:id])
  end
  
  def new
    @site = Site.new :name => params[:site_name]
  end
  
  def create
    @site = Site.new(params[:site])
    if @site.save
      flash[:notice] = 'Site was successfully created.'
      redirect_to :controller => 'identities', :action => 'new', :site_id => @site.id
    else
      render :action => 'new'
    end
  end
  
  def edit
    @site = Site.find(params[:id])
  end
  
  def update
    @site = Site.find(params[:id])
    if @site.update_attributes(params[:site])
      flash[:notice] = 'Site was successfully updated.'
      redirect_to :action => 'show', :id => @site
    else
      render :action => 'edit'
    end
  end
  
  def destroy
    Site.find(params[:id]).destroy
    redirect_to :action => 'list'
  rescue ActiveRecord::StatementInvalid
    flash[:error] = "The site has related identities"
    render :template => 'error_page.rhtml'
  end
end
